import React, { forwardRef, memo, useRef, useImperativeHandle } from "react"

const HelloWorld = memo(
    forwardRef((props, ref) => {
        const inputRef = useRef()

        // 子组件对父组件传入的ref进行处理
        useImperativeHandle(ref, () => {
            return {
                focus() {
                    inputRef.current.focus()
                    // console.log("focus")
                },
                resetValue() {
                    inputRef.current.value = ""
                },
            }
        })

        return (
            <div>
                <input type="text" ref={inputRef} />
            </div>
        )
    })
)

const App = memo(() => {
    const titleRef = useRef()
    const inputRef = useRef()

    function handleDOM() {
        console.log(titleRef.current)
        // console.log(inputRef.current)

        inputRef.current.focus()
        inputRef.current.resetValue()
    }

    return (
        <div>
            <h2 ref={titleRef}>哈哈哈</h2>
            <button onClick={handleDOM}>DOM操作</button>
            <HelloWorld ref={inputRef}></HelloWorld>
        </div>
    )
})

export default App
